<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>算法执行演示</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        
        .container {
            background-color: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        h1 {
            color: #333;
            text-align: center;
        }
        
        .upload-section, .execute-section {
            margin: 20px 0;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        
        .upload-section h2, .execute-section h2 {
            margin-top: 0;
            color: #555;
        }
        
        .file-upload-group {
            margin: 15px 0;
        }
        
        .file-upload-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        
        .button-group {
            text-align: center;
            margin: 20px 0;
        }
        
        button {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 12px 24px;
            font-size: 16px;
            border-radius: 4px;
            cursor: pointer;
            margin: 0 10px;
        }
        
        button:hover {
            background-color: #0056b3;
        }
        
        button:disabled {
            background-color: #6c757d;
            cursor: not-allowed;
        }
        
        .status {
            margin: 20px 0;
            padding: 15px;
            border-radius: 4px;
            text-align: center;
        }
        
        .status.info {
            background-color: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }
        
        .status.success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .status.error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .log {
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 4px;
            padding: 15px;
            height: 300px;
            overflow-y: auto;
            font-family: monospace;
            white-space: pre-wrap;
        }
        
        .hidden {
            display: none;
        }
        
        select, input[type="file"] {
            width: 100%;
            padding: 8px;
            margin: 5px 0 15px 0;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>算法执行演示</h1>
        
        <!-- 文件上传部分 -->
        <div class="upload-section">
            <h2>文件上传</h2>
            <p>请先获取批次ID，然后上传路线和货物CSV文件</p>
            
            <div class="button-group">
                <button id="allocateBatchBtn">获取批次ID</button>
            </div>
            
            <div class="file-upload-group">
                <label for="batchId">批次ID:</label>
                <input type="number" id="batchId" value="" readonly>
            </div>
            
            <div class="file-upload-group">
                <label for="routeFile">路线文件:</label>
                <input type="file" id="routeFile" accept=".csv">
            </div>
            
            <div class="file-upload-group">
                <label for="shipmentFile">货物文件:</label>
                <input type="file" id="shipmentFile" accept=".csv">
            </div>
            
            <div class="button-group">
                <button id="uploadRouteBtn">上传路线文件</button>
                <button id="uploadShipmentBtn">上传货物文件</button>
            </div>
        </div>
        
        <!-- 算法执行部分 -->
        <div class="execute-section">
            <h2>算法执行</h2>
            <p>执行已上传的文件批次</p>
            
            <div class="file-upload-group">
                <label for="executeBatchId">批次ID:</label>
                <input type="number" id="executeBatchId" value="">
            </div>
            
            <div class="button-group">
                <button id="syncBtn">同步执行算法</button>
                <button id="asyncBtn">异步执行算法</button>
            </div>
        </div>
        
        <div id="status" class="status hidden"></div>
        
        <h3>执行日志:</h3>
        <div id="log" class="log"></div>
    </div>

    <script>
        // 全局变量
        let eventSource = null;
        
        // DOM元素
        const allocateBatchBtn = document.getElementById('allocateBatchBtn');
        const batchIdInput = document.getElementById('batchId');
        const executeBatchIdInput = document.getElementById('executeBatchId');
        const routeFileInput = document.getElementById('routeFile');
        const shipmentFileInput = document.getElementById('shipmentFile');
        const uploadRouteBtn = document.getElementById('uploadRouteBtn');
        const uploadShipmentBtn = document.getElementById('uploadShipmentBtn');
        const syncBtn = document.getElementById('syncBtn');
        const asyncBtn = document.getElementById('asyncBtn');
        const statusDiv = document.getElementById('status');
        const logDiv = document.getElementById('log');
        
        // API基础URL
        const API_BASE_URL = 'http://localhost:8080';
        
        // 显示状态信息
        function showStatus(message, type = 'info') {
            statusDiv.textContent = message;
            statusDiv.className = `status ${type}`;
            statusDiv.classList.remove('hidden');
            
            // 添加到日志
            addToLog(`[${new Date().toLocaleTimeString()}] ${message}`);
        }
        
        // 添加日志
        function addToLog(message) {
            logDiv.textContent += message + '\n';
            logDiv.scrollTop = logDiv.scrollHeight;
        }
        
        // 禁用按钮
        function disableButtons() {
            allocateBatchBtn.disabled = true;
            uploadRouteBtn.disabled = true;
            uploadShipmentBtn.disabled = true;
            syncBtn.disabled = true;
            asyncBtn.disabled = true;
        }
        
        // 启用按钮
        function enableButtons() {
            allocateBatchBtn.disabled = false;
            uploadRouteBtn.disabled = false;
            uploadShipmentBtn.disabled = false;
            syncBtn.disabled = false;
            asyncBtn.disabled = false;
        }
        
        // 获取批次ID
        async function allocateBatchId() {
            try {
                disableButtons();
                showStatus('正在获取批次ID...', 'info');
                
                const response = await fetch(`${API_BASE_URL}/api/upload/batch`, {
                    method: 'POST'
                });
                
                const result = await response.json();
                
                if (result.code === 200) {
                    batchIdInput.value = result.data;
                    executeBatchIdInput.value = result.data;
                    showStatus(`批次ID获取成功: ${result.data}`, 'success');
                } else {
                    showStatus(`批次ID获取失败: ${result.message}`, 'error');
                }
            } catch (error) {
                showStatus(`获取批次ID时发生错误: ${error.message}`, 'error');
            } finally {
                enableButtons();
            }
        }
        
        // 上传路线文件
        async function uploadRouteFile() {
            const file = routeFileInput.files[0];
            const batchId = batchIdInput.value;
            
            if (!batchId) {
                showStatus('请先获取批次ID', 'error');
                return;
            }
            
            if (!file) {
                showStatus('请选择路线文件', 'error');
                return;
            }
            
            try {
                disableButtons();
                showStatus(`正在上传路线文件，批次ID: ${batchId}...`, 'info');
                
                const formData = new FormData();
                formData.append('file', file);
                formData.append('batchId', batchId);
                
                const response = await fetch(`${API_BASE_URL}/api/upload/routes`, {
                    method: 'POST',
                    body: formData
                });
                
                const result = await response.json();
                
                if (result.code === 200) {
                    showStatus(`路线文件上传成功: ${result.message}`, 'success');
                } else {
                    showStatus(`路线文件上传失败: ${result.message}`, 'error');
                }
            } catch (error) {
                showStatus(`上传路线文件时发生错误: ${error.message}`, 'error');
            } finally {
                enableButtons();
            }
        }
        
        // 上传货物文件
        async function uploadShipmentFile() {
            const file = shipmentFileInput.files[0];
            const batchId = batchIdInput.value;
            
            if (!batchId) {
                showStatus('请先获取批次ID', 'error');
                return;
            }
            
            if (!file) {
                showStatus('请选择货物文件', 'error');
                return;
            }
            
            try {
                disableButtons();
                showStatus(`正在上传货物文件，批次ID: ${batchId}...`, 'info');
                
                const formData = new FormData();
                formData.append('file', file);
                formData.append('batchId', batchId);
                
                const response = await fetch(`${API_BASE_URL}/api/upload/shipments`, {
                    method: 'POST',
                    body: formData
                });
                
                const result = await response.json();
                
                if (result.code === 200) {
                    showStatus(`货物文件上传成功: ${result.message}`, 'success');
                } else {
                    showStatus(`货物文件上传失败: ${result.message}`, 'error');
                }
            } catch (error) {
                showStatus(`上传货物文件时发生错误: ${error.message}`, 'error');
            } finally {
                enableButtons();
            }
        }
        
        // 同步执行算法
        async function executeSync() {
            const batchId = executeBatchIdInput.value;
            
            if (!batchId) {
                showStatus('请输入批次ID', 'error');
                return;
            }
            
            try {
                disableButtons();
                showStatus(`正在同步执行算法，批次ID: ${batchId}...`, 'info');
                
                const response = await fetch(`${API_BASE_URL}/api/algorithm/execute?dataId=${batchId}`, {
                    method: 'POST'
                });
                
                const result = await response.json();
                
                if (result.code === 200) {
                    showStatus(`算法执行成功: ${result.message}`, 'success');
                } else {
                    showStatus(`算法执行失败: ${result.message}`, 'error');
                }
            } catch (error) {
                showStatus(`执行过程中发生错误: ${error.message}`, 'error');
            } finally {
                enableButtons();
            }
        }
        
        // 异步执行算法
        async function executeAsync() {
            const batchId = executeBatchIdInput.value;
            
            if (!batchId) {
                showStatus('请输入批次ID', 'error');
                return;
            }
            
            try {
                disableButtons();
                showStatus(`正在启动异步算法执行，批次ID: ${batchId}...`, 'info');
                
                // 启动异步任务
                const response = await fetch(`${API_BASE_URL}/api/algorithm/execute/async?dataId=${batchId}`, {
                    method: 'POST'
                });
                
                const result = await response.json();
                
                if (result.code === 200) {
                    // 从返回消息中提取任务ID
                    const match = result.message.match(/任务ID: ([\w-]+)/);
                    if (match && match[1]) {
                        const taskId = match[1];
                        showStatus(`异步任务已启动，任务ID: ${taskId}`, 'info');
                        
                        // 建立SSE连接监听任务状态
                        connectToSSE(taskId);
                    } else {
                        showStatus('无法获取任务ID', 'error');
                        enableButtons();
                    }
                } else {
                    showStatus(`启动异步任务失败: ${result.message}`, 'error');
                    enableButtons();
                }
            } catch (error) {
                showStatus(`启动异步任务时发生错误: ${error.message}`, 'error');
                enableButtons();
            }
        }
        
        // 建立SSE连接
        function connectToSSE(taskId) {
            // 关闭之前的连接（如果存在）
            if (eventSource) {
                eventSource.close();
            }
            
            // 建立新的SSE连接
            eventSource = new EventSource(`${API_BASE_URL}/api/algorithm/sse/status/${taskId}`);
            
            eventSource.addEventListener('taskStatus', function(event) {
                const result = JSON.parse(event.data);
                
                if (result.code === 200) {
                    showStatus(`算法执行完成: ${result.message}`, 'success');
                } else {
                    showStatus(`算法执行失败: ${result.message}`, 'error');
                }
                
                // 关闭连接并启用按钮
                eventSource.close();
                enableButtons();
            });
            
            eventSource.onerror = function(error) {
                showStatus('SSE连接发生错误', 'error');
                eventSource.close();
                enableButtons();
            };
        }
        
        // 绑定事件
        allocateBatchBtn.addEventListener('click', allocateBatchId);
        uploadRouteBtn.addEventListener('click', uploadRouteFile);
        uploadShipmentBtn.addEventListener('click', uploadShipmentFile);
        syncBtn.addEventListener('click', executeSync);
        asyncBtn.addEventListener('click', executeAsync);
        
        // 页面加载完成后的初始化
        document.addEventListener('DOMContentLoaded', function() {
            addToLog('算法执行演示页面已加载');
        });
    </script>
</body>
</html>